//
//  KLMHomeManageController.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/11.
//

import UIKit

class KLMHomeManageController: KLMBaseHomeTableController {
    
    private var homeList: [KLMHomeParticipant]? = {
        return KLMHomeList.getHomeList()
    }()
    private var noHome = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(loadHomeList(_:)), name: .homeNameChanged, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(loadHomeList(_:)), name: .deleteHomeSuccess, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(loadHomeList(_:)), name: .createHomeSuccess, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(loadHomeList(_:)), name: .homeInfoChanged, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(loadHomeList(_:)), name: .joinHomeSuccess, object: nil)
        
        homeItems = KLMHomeItem.homeListItems()
        loadHomeList(nil)
        view.backgroundColor = rgba(243, 243, 246, 1)
        
        guard titleText != nil else {
            title = "家庭管理"
            return
        }
    }
    override func loadDataRefreshUI() {
        super.loadDataRefreshUI()
        loadHomeList(nil)
    }
    
    override func viewDidLoadConfig() {
        super.viewDidLoadConfig()
    }
    
    @objc func loadHomeList(_ notify: Notification?) {
        SVProgressHUD.show()
        KLMRequest.queryHomeList { response in
            SVProgressHUD.dismiss()
            if let homes = response as? [KLMHomeParticipant] {
                KLMHomeList.saveHomeList(list: homes)
                self.homeList = homes
                if homes.count > 0 {
                    self.homeItems[0] = homes.map({KLMHomeItem(type: .normal, title: $0.meshName, showArrow: true)})
                } else {
                    self.homeItems[0] = [KLMHomeItem(type: .normal, title: "我的家...", showArrow: true)]
                }
                self.noHome = homes.count == 0
                self.tableView.reloadData()
            }
            self.endHeaderRefresh()
        } failure: { error in
            SVProgressHUD.dismiss()
            self.endHeaderRefresh()
            KLMHttpShowError(error)
        }
    }
    
    /// 请求家庭设置页数据
    func loadInfoAndMembers(homeId: Int, successBlock: @escaping (_ info: KLMHomeInfo, _ users: [KLMHomeUser]) -> (), failureBlock: @escaping ([Error]) -> ()) {
        
        var info: KLMHomeInfo?
        var users: [KLMHomeUser]?
        
        let group = DispatchGroup()
        var errors: [Error] = []        // 存储所有请求的错误
        group.enter()
        SVProgressHUD.show()
        KLMRequest.getHomeInfo(id: homeId) { response in
            group.leave()
            SVProgressHUD.dismiss()
            if let infoData = response as? KLMHomeInfo {
                info = infoData
            }
        } failure: { error in
            errors.append(error)
            KLMHttpShowError(error)
            group.leave()
        }
        group.enter()
        KLMRequest.getHomeUsers(meshId: homeId) { response in
            print("info请求线程", Thread.current)
            group.leave()
            SVProgressHUD.dismiss()
            if let userList = response as? KLMHomeUserList {
                users = userList.data
            }
        } failure: { error in
            SVProgressHUD.dismiss()
            errors.append(error)
            KLMHttpShowError(error)
            group.leave()
        }
        // 所有请求完成后的回调
        group.notify(queue: .main) {
            if !errors.isEmpty {
                
                failureBlock(errors)
                return
            }
            if let homeInfo = info, let users = users {
                successBlock(homeInfo, users)
            }
        }
    }
    
    override func tableViewDidSelect(item: KLMHomeItem, at: IndexPath, on: UITableView) {
        super.tableViewDidSelect(item: item, at: at, on: on)
        if item.type == .normal {
            if noHome {
                let vc = KLMCreateHomeController()
                vc.titleText = item.title
                navigationController?.pushViewController(vc, animated: true)
            } else {
                let homeId = homeList![at.row].id
                let vc = KLMHomeSettingController(homeId: homeId)
                vc.titleText = "家庭设置"
                self.navigationController?.pushViewController(vc, animated: true)
            }
        } else if item.actionType == .createHome {
            /// 创建家庭
            let vc = KLMCreateHomeController()
            vc.titleText = item.title
            navigationController?.pushViewController(vc, animated: true)
        } else if item.actionType == .joinHome {
            /// 加入家庭
            let vc = KLMJoinHomeController()
            vc.titleText = item.title
            navigationController?.pushViewController(vc, animated: true)
        }
    }
}


